package edu.zut.controller;

import edu.zut.dao.UserDao;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//处理登录的控制器（servlet）
public class UserLoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设定编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=utf-8");
        //获取登录请求参数
        String user_name = request.getParameter("user_name");
        String user_psw = request.getParameter("user_psw");
        System.out.println("user_name = " + user_name);
        System.out.println("user_psw = " + user_psw);

        String error;
        //校验用户名和密码是否为空
        if (null == user_name || user_name.trim().length() == 0
                || null == user_psw || user_psw.trim().length() == 0
        ) {
            //返回登录页面并告诉用户用户名或密码不能为空
            error = "用户名或密码不能为空";
            //web中如何进行资源的跳转
            //重定向   由响应发起的   /表示的是web服务器的资源路劲  但是不能卸载信息
            //response.sendRedirect(request.getContextPath() + "/html/login.html");
            //将需要和其他web资源共享的信息存入到request中
            request.setAttribute("error", error);
            //转发  / 表示的当前应用程序的上下文路劲  1、获取一个转发器(指定转发的资源)    2、执行转发操作
            RequestDispatcher dispatcher = request.getRequestDispatcher("/loginPage");
            dispatcher.forward(request, response);
        } else {
            //如果不为空，校验是否存在,调用数据层的操作进行校验
            UserDao userDao = new UserDao();
            boolean result = userDao.loginQuery(user_name, user_psw);
            if (result) {
                //用户名和密码正确，跳转到用户首页
                request.setAttribute("name", user_name);
                request.getRequestDispatcher("/indexPage").forward(request, response);
            } else {
                error = "用户名或密码错误";
                //登录失败返回登录页面并携带错误信息
                request.setAttribute("error", error);
                request.getRequestDispatcher("/loginPage").forward(request, response);
            }
        }


    }
}
